package com.csdj.springcloudt309.order.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.csdj.spingcloudt309.common.entity.User;
import com.csdj.springcloudt309.order.service.UserServiceRpc;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private UserServiceRpc userServiceRpc;

    @GetMapping("/test")
    public User test(String serviceId,String reqUrl,Class<User> clazz){
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        if(instances.size()>0){
            //取第一个， 真实环境由负载均衡策略决定
            ServiceInstance instance = instances.get(0);
            String url = String.format("%s://%s:%s/"+reqUrl+"/%d",instance.getScheme(),instance.getHost(),instance.getPort(),8);
            RestTemplate restTemplate = new RestTemplate();
            User user = restTemplate.getForObject(url,clazz);
            if(user != null){
                System.out.println("获取用户数据");
                return user;
            }else{
                return new User();
            }
        }
        System.out.println("用户节点失效");
        return new User();
    }

    @GetMapping("discovery")
    public String testDiscovery(HttpServletRequest request){
        String uname = request.getHeader("uname");
        System.out.println(String.format("header: %s=%s","uname",uname));
        //获取发现服务中所有注册的模块
        List<String> services = discoveryClient.getServices();
        for(String app:services){
            System.out.println(app);
            List<ServiceInstance> instances = discoveryClient.getInstances(app);
            for(ServiceInstance instance : instances){
                System.out.println(String.format("scheme:%s,host:%s,port:%s",instance.getScheme(),instance.getHost(),instance.getPort()));
            }
        }
        return "test";
    }

    /**
     * 通过负载均衡来选择节点， 进行远程请求
     * @return
     */
    @HystrixCommand(fallbackMethod = "loadbalanceFallback")
    @GetMapping("/balance")
    public User loadBalance(){
        User user = restTemplate.getForObject("http://user/user/info/3", User.class);
        if(user != null){
            System.out.println("通过负载均衡获取用户信息");
            return user;
        }
        return new User();
    }

    public User loadbalanceFallback(){
        System.out.println("执行方法异常");
        return new User();
    }

    @GetMapping("/feign")
    public User feign(){
        return userServiceRpc.getUserInfo(3);
    }

    @GetMapping("/add")
    public int addUser(){
        User user = new User();
        user.setNickName("cloud");
        user.setTopId(0);
        user.setEmail("test@test.com");
        user.setUsername("cloud");
        user.setBirthday(LocalDate.now());
        user.setCreateTm(LocalDateTime.now());
        user.setInviteCode("2343");
        user.setAddress("csdj");
        user.setPassword("23123232");
        return userServiceRpc.saveUser(user);
    }

}
